package org.systm.security.init;

import lombok.Getter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.systm.adminuser.entity.AdminUser;
import org.systm.adminuser.entity.UserPermission;
import org.systm.adminuser.entity.UserRole;
import org.systm.adminuser.service.AdminUserService;
import org.systm.adminuser.service.UserPermissionService;
import org.systm.adminuser.service.UserRoleService;
import org.systm.adminuser.service.condition.AdminUserQuery;
import org.systm.adminuser.service.condition.UserRoleQuery;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class InitUser {
    @Resource
    AdminUserService adminUserService;

    @Resource
    UserPermissionService permissionService;

    @Resource
    UserRoleService userRoleService;

    @Resource
    PasswordEncoder passwordEncoder;

    @Getter
    private final String username = "admin";
    @Getter
    private final String password = "admin@123";
    @Getter
    private final String roleName = "admin";

    public void initAdmin() {
        Optional<UserRole> roleOp = userRoleService.findOne(UserRoleQuery.getByRoleName().apply(getRoleName()));
        if (roleOp.isEmpty()) roleOp = Optional.of(createUserRole());
        Optional<List<UserPermission>> permissionAll = permissionService.findAll();
        if (permissionAll.isPresent()) {
            List<UserPermission> cache = permissionAll.get();
            // 直接覆盖，简单有效
            roleOp.get().setPermissions(cache);
            roleOp = Optional.of(userRoleService.repository().save(roleOp.get()));
        }

        Optional<AdminUser> adminUserOp = adminUserService.findOne(AdminUserQuery.getExistsUsername().apply(username));
        if (adminUserOp.isEmpty()) adminUserOp = Optional.of(createAdminUser(roleOp.get()));
        List<UserRole> userRoles = new ArrayList<>();
        userRoles.add(roleOp.get());
        adminUserOp.get().setRoles(userRoles);
        adminUserService.repository().save(adminUserOp.get());
    }

    private AdminUser createAdminUser(UserRole userRole) {
        List<UserRole> userRoles = new ArrayList<>();
        userRoles.add(userRole);
        return AdminUser.builder()
                .username(getUsername())
                .password(passwordEncoder.encode(getPassword()))
                .nickname("超级管理员")
                .salt(UUID.randomUUID().toString())
                .photo("not")
                .roles(userRoles)
                .build();
    }

    private UserRole createUserRole() {
        return UserRole.builder()
                .role(getRoleName())
                .permissions(permissionService.findAll().orElse(null))
                .build();
    }
}
